package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constat.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @authou: fu
 * @date:Created in 2019/12/2
 * @description:
 * @version:1.0
 */
@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;

    public void add(Integer[] checkgroupIds, Setmeal setmeal) {

        setmealDao.add(setmeal);

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(checkgroupIds,setmeal.getId());
        }
        savePic2Redis(setmeal.getImg());
    }

    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    public void setSetmealAndCheckGroup(Integer[] checkgroupIds, Integer setmealId) {
        for (Integer checkGroupId : checkgroupIds) {
            Map map = new HashMap();
            map.put("setmealId",setmealId);
            map.put("checkGroupId",checkGroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }

    private void savePic2Redis(String pic){
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
        jedis.close();
    }

    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

}
